extends Node
class_name Economy

signal money_changed(new_amount: int)
signal transaction_completed(item_id: String, count: int, total_price: int, is_buy: bool)

var money := 100
var inventory: Inventory
var crop_system: CropSystem

func _ready():
	pass

func set_inventory(inv: Inventory):
	inventory = inv

func set_crop_system(cs: CropSystem):
	crop_system = cs

func set_money(amount: int):
	money = max(0, amount)
	money_changed.emit(money)

func add_money(amount: int):
	set_money(money + amount)

func spend_money(amount: int) -> bool:
	if money >= amount:
		set_money(money - amount)
		return true
	return false

func get_money() -> int:
	return money

func buy_item(item_id: String, count: int) -> bool:
	if count <= 0:
		return false
	
	var unit_price = get_buy_price(item_id)
	if unit_price <= 0:
		return false
	
	var total_price = unit_price * count
	
	if not spend_money(total_price):
		return false
	
	if not inventory.add_item(item_id, count):
		# 如果添加失败，退还金钱
		add_money(total_price)
		return false
	
	transaction_completed.emit(item_id, count, total_price, true)
	return true

func sell_item(item_id: String, count: int) -> bool:
	if count <= 0:
		return false
	
	if not inventory.has_item(item_id, count):
		return false
	
	var unit_price = get_sell_price(item_id)
	if unit_price <= 0:
		return false
	
	var total_price = unit_price * count
	
	if not inventory.remove_item(item_id, count):
		return false
	
	add_money(total_price)
	transaction_completed.emit(item_id, count, total_price, false)
	return true

func get_buy_price(item_id: String) -> int:
	if crop_system == null:
		return 0
	
	return crop_system.get_seed_price(item_id)

func get_sell_price(item_id: String) -> int:
	if crop_system == null:
		return 0
	
	return crop_system.get_crop_sell_price(item_id)

func can_afford(item_id: String, count: int) -> bool:
	var unit_price = get_buy_price(item_id)
	return money >= (unit_price * count)

func get_shop_items() -> Array:
	return [
		{
			"id": "seed_turnip",
			"name": "萝卜种子",
			"price": get_buy_price("seed_turnip"),
			"description": "生长快速的萝卜种子"
		},
		{
			"id": "seed_potato",
			"name": "土豆种子", 
			"price": get_buy_price("seed_potato"),
			"description": "营养丰富的土豆种子"
		},
		{
			"id": "seed_corn",
			"name": "玉米种子",
			"price": get_buy_price("seed_corn"),
			"description": "高价值的玉米种子"
		}
	]

func get_sellable_items() -> Array:
	var sellable := []
	var items = inventory.get_items()
	
	for item in items:
		if item.id != "" and item.count > 0:
			var sell_price = get_sell_price(item.id)
			if sell_price > 0:
				sellable.append({
					"id": item.id,
					"name": inventory.get_item_name(item.id),
					"count": item.count,
					"price": sell_price,
					"total_value": sell_price * item.count
				})
	
	return sellable